package com.by.controller;



import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;



import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;

import cn.dreampie.captcha.CaptchaRender;
import cn.dreampie.shiro.core.SubjectKit;

import com.alibaba.fastjson.JSONObject;
import com.by.config.SystemConfig;
import com.by.model.Admin;
import com.by.model.Article;
import com.by.model.Member;
import com.by.model.Message;
import com.by.model.Orders;
import com.by.model.Product;
import com.by.model.User;
import com.by.util.Constant;
import com.by.util.ImageCode;
import com.by.util.SystemConfigUtil;
import com.by.util.Util;
import com.jfinal.aop.Clear;
import com.jfinal.ext.plugin.shiro.ShiroMethod;







public class AdminController extends BaseAdminController<Admin> {
    
	        /**
	         * 后台首页，登陆流程到这里
	         * 触发拦截器   ： AdminInterceptor(此拦截器触发在执行到BaseAdminController之前，打开BaseAdminController即知)
	         * 
	         * 执行此方法需要有admin 权限   并且 具有 "ROLE_ADMIN","ROLE_SERVICE"  角色之一
	         */
			@RequiresRoles(value={"ROLE_ADMIN","ROLE_SERVICE"},logical=Logical.OR)
			@RequiresPermissions("admin")
			public void index(){	
				setAttr("java_version", System.getProperty("java.version"));
				setAttr("os", System.getProperty("os.name"));
				setAttr("os_arch", System.getProperty("os.arch"));
				setAttr("os_version", System.getProperty("os.version"));
				setAttr("user_dir", System.getProperty("user.dir"));
				setAttr("tmpdir", System.getProperty("java.io.tmpdir"));	
				
				setAttr("unprocessedOrderCount", getUnprocessedOrderCount());// 未处理订单
				setAttr("paidUnshippedOrderCount", getPaidUnshippedOrderCount()); // 等待发货订单数
				setAttr("unreadMessageCount", getUnreadMessageCount()); // 未读消息
				setAttr("storeAlertCount", getStoreAlertCount()); // 商品库存报警
				
				setAttr("marketableProductCount", getMarketableProductCount()); // 已上架商品
				setAttr("unMarketableProductCount", getUnMarketableProductCount()); // 已下架商品
				setAttr("memberTotalCount", getMemberTotalCount()); // 会员总数
				setAttr("articleTotalCount", getArticleTotalCount()); // 文章总数
				
				render("/admin/admin_index.html");
			}	
			// 获取未处理订单数
			public Long getUnprocessedOrderCount() {
				return Orders.dao.getUnprocessedOrderCount();
			}
			
			// 获取已支付未发货订单数
			public Long getPaidUnshippedOrderCount() {
				return Orders.dao.getPaidUnshippedOrderCount();
			}
			
			// 获取未读消息数
			public Long getUnreadMessageCount() {
				return Message.dao.getUnreadMessageCount();
			}
			
			// 获取商品库存报警数
			public Long getStoreAlertCount() {
				return Product.dao.getStoreAlertCount();
			}
			
			// 获取已上架商品数
			public Long getMarketableProductCount() {
				return Product.dao.getMarketableProductCount();
			}
			
			// 获取已下架商品数
			public Long getUnMarketableProductCount() {
				return Product.dao.getUnMarketableProductCount();
			}
			
			// 获取会员总数
			public Long getMemberTotalCount() {
				return Member.dao.getTotalCount();
			}
			
			// 获取文章总数
			public Long getArticleTotalCount() {
				return Article.dao.getTotalCount();
			}
    @Clear		
	public void login(){
		SystemConfig systemConfig = SystemConfigUtil.getSystemConfig();
		setAttr("systemConfig", systemConfig);
		setAttr("base", getRequest().getContextPath());
	    System.out.println("路径： "+getRequest().getContextPath());
		render("/admin/login.html");
	}
	@Clear
	public void loginVerify(){
		
		String username = getPara("username");
		String password = getPara("password");
		String imageCode = getPara("imageCode");//验证码
		boolean isRember = getPara("remember","").equalsIgnoreCase("on")?true:false;
		
		if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password))
		{
			renderErrorMessage("用户名或者密码不能为空");
			return ;
		}
//		if(!getSession().getAttribute(ImageCode.class.getName()).toString().equalsIgnoreCase(imageCode))
//		{
//			renderErrorMessage("验证码错误");
//			return ;
//		}
		//另一种验证码生成判断
		if(!SubjectKit.doCaptcha("captcha", imageCode))
		{
			renderErrorMessage("验证码错误");
			return ;
		}
		Admin admin = Admin.dao.getAdminByUsername(username);
	
		Subject currentAmdin = SecurityUtils.getSubject();
        
		System.out.println(username+":"+password+":"+imageCode);
		
		UsernamePasswordToken token = new UsernamePasswordToken(username, DigestUtils.md5Hex(password));
        
		token.setRememberMe(isRember);
		try {
		
			currentAmdin.login(token);
			render("login.html");
			
		} catch (UnknownAccountException e) {
		
			token.clear();
			renderErrorMessage(Constant.NO_USER);
			return;
		} catch (IncorrectCredentialsException ie) {
			token.clear();
			SystemConfig systemConfig = getSystemConfig();
			if (systemConfig.getIsLoginFailureLock()) {
				int loginFailureLockCount = getSystemConfig().getLoginFailureLockCount();
				int loginFailureCount = admin.getInt("loginFailureCount") + 1;
				if (loginFailureCount >= systemConfig.getLoginFailureLockCount()) {
					admin.set("isAccountLocked", true);
					admin.set("lockedDate", new Date());
					admin.update();
				}
				admin.set("loginFailureCount", loginFailureCount);
				updated(admin);
				if (loginFailureLockCount - loginFailureCount <= 3) {
					renderErrorMessage("若连续" + loginFailureLockCount + "次密码输入错误,您的账号将被锁定,还有" + (loginFailureLockCount - admin.getInt("loginFailureCount")) + " 次机会。");
					return;
				} else {
					renderErrorMessage(Constant.UserOrPass_error);
					return;
				}
			} else {
				renderErrorMessage(Constant.UserOrPass_error);
				return;
			}
		} catch(LockedAccountException le){
			token.clear();
			renderErrorMessage(Constant.UserClock);
			return;
		} catch (RuntimeException re) {
			re.printStackTrace();
			token.clear();
			renderErrorMessage(Constant.Login_fail);
			return;
		}
			
		// 登录成功后
			if(ShiroMethod.authenticated()) {
					admin.set("loginDate", new Date());
					admin.set("loginIp", getRequest().getRemoteAddr());
					admin.set("loginFailureCount", 0);
					updated(admin);
					//renderSuccessMessage("GOOD LUNCY");
					redirect("/admin/main");
				} 
		
	}
	// 后台主页面
	public void main(){
			setAttr("loginUsername", getLoginAdminName());
			setAttr("countMail",getUnreadMessageCount());
			render("/admin/admin_main.html");
		}
	
	
	public void regist() throws UnsupportedEncodingException{
		JSONObject json = new JSONObject();
		json.put("status", 2);

		User user = getModel(User.class);
		
		String password = getPara("password");
		String password2 = getPara("password2");
		String key = user.getStr("email");
		String realname = user.getStr("realname");
		
		String imageCode = getSessionAttr(ImageCode.class.getName());
		String checkCode = this.getPara("imageCode");
		
		if(Util.isEmpty(checkCode)||!imageCode.equalsIgnoreCase(checkCode))
		{
			json.put("msg", "");
			renderJson(json.toJSONString());
			return;
		}
		
		if (Util.isEmpty(key) || key.indexOf("@") < 0) {
			json.put("msg","");
			renderJson(json.toJSONString());
			return;
		}
		if ( Util.isEmpty(realname) //
				|| Util.isEmpty(password) || Util.isEmpty(password2) //
				|| password.length() < 6 || !password.equals(password2)) {
			json.put("msg", "");
			renderJson(json.toJSONString());
			return;
		}
	
		List<User> newUsers = User.dao.find("select * from by_user where username = '"+key+"'");
		System.out.println("size: "+newUsers.size());
		if (newUsers.size() >= 1) {
			json.put("msg", "");
			renderJson(json.toJSONString());
			return;
		}
		
	     new User().set("username", key)
	               .set("realname", realname)
		           .set("password", Util.Md5ecode(password))
		           .set("usertype", 3)
		           .set("departid", Constant.DEPART_REGIST_ID)
		           .set("create_time", Util.getNow())
		           .set("create_id", 1).save();
	
		
		json.put("status", 1);

		renderJson(json.toJSONString());
	}
	@Clear
	public void image_code(){
		int width = 100, height = 45, minnum = 0, maxnum = 0, fontsize = 35;
		CaptchaRender captcha = new CaptchaRender();
		
		if (width > 0 && height > 0)
			captcha.setImgSize(width, height);
		
		if (minnum > 0 && maxnum > 0)
			captcha.setFontNum(minnum, maxnum);
		if (fontsize > 0)
			captcha.setFontSize(fontsize, fontsize);
		// 干扰线数量 默认0
		captcha.setLineNum(1);
		// 噪点数量 默认50
		captcha.setArtifactNum(10);
		// 使用字符 去掉0和o 避免难以确认
		captcha.setCode("123456789");
		 //验证码在session里的名字 默认 captcha,创建时间为：名字_time
		// captcha.setCaptchaName("captcha");
	    //验证码颜色 默认黑色
		// captcha.setDrawColor(new Color(255,0,0));
	    //背景干扰物颜色  默认灰
		// captcha.setDrawBgColor(new Color(0,0,0));
	    //背景色+透明度 前三位数字是rgb色，第四个数字是透明度  默认透明
		// captcha.setBgColor(new Color(225, 225, 0, 100));
	    //滤镜特效 默认随机特效 //曲面Curves //大理石纹Marble //弯折Double //颤动Wobble //扩散Diffuse
		captcha.setFilter(CaptchaRender.FilterFactory.Curves);
		// 随机色 默认黑验证码 灰背景元素
		captcha.setRandomColor(true);
		render(captcha);
		
		/**
		 * 另一种验证码的生成方式
		 */
//           try {
//             new ImageCode().doGet(getRequest(), getResponse());
//			
//			} catch (ServletException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//	

	}
	
	
}
